package com.qk.management.aop;

import cn.hutool.json.JSONUtil;
import com.qk.common.Result;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.entity.OperateLog;
import com.qk.management.mapper.OperateLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class LogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;
    @Pointcut("@annotation(com.qk.management.aop.anno.LogAnno)")
    public void pt(){}

    @Around("pt()")
    public Object log(ProceedingJoinPoint pjp) {
        Object returnValue;
        try {
            long startTime = System.currentTimeMillis();
            LocalDateTime operateTime = LocalDateTime.now();
            returnValue = pjp.proceed();
            String result = JSONUtil.toJsonStr(returnValue);
            long endTime = System.currentTimeMillis();
            OperateLog operateLog = OperateLog.builder()
                    .className(pjp.getTarget().getClass().getName())
                    .operateUserId(CurrentUserContextHolders.get())
                    .methodName(pjp.getSignature().getName())
                    .methodParams(Arrays.toString(pjp.getArgs()))
                    .returnValue(result)
                    .className(pjp.getTarget().getClass().getName())
                    .costTime(endTime - startTime)
                    .operateTime(operateTime)
                    .build();
            try {
                operateLogMapper.insert(operateLog);
            } catch (Exception e) {
                log.error("操作日志插入异常", e);
            }
        } catch (Throwable e) {
            returnValue = Result.error("您的操作失败，请稍后重试！");
            log.error("操作失败:{}", e.getMessage());
        }
        return returnValue;
    }

}
